<template>
  <div class="view-fill">
    <div v-show="!detailInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :needReturn="!flowFormType"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button
            @click="saveAndSubmit()"
            v-if="
              !id && $permission('adverseEvent:saveAndSubmit') && !flowFormType
            "
            >保存并提交</el-button
          >
          <el-button v-if="!flowFormType" @click="save()">保存</el-button>
        </template>
        <!--基础信息-->
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.baseRef"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-deviceName>
                <el-input
                  v-model="formInfo.data.deviceName"
                  type="input"
                  :disabled="true"
                  class="not-mongolia"
                  placeholder="请选择设备"
                >
                  <template #append>
                    <el-icon @click="openAssetArchivesDialog"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              // 选择计量器具
              <template v-slot:form-measuringInstrumentName>
                <el-input
                  v-model="formInfo.data.measuringInstrumentName"
                  type="input"
                  :disabled="true"
                  class="not-mongolia"
                  placeholder="请选择计量器具"
                >
                  <template #append>
                    <el-icon @click="openAdverseDialog"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>
        <!-- 不良事件情况 -->
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('adverseEventInfo') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.adverseEventRef"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.adverseEventFieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-happenTime>
                <el-date-picker
                  v-model="formInfo.data.happenTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择事件发生时间"
                />
              </template>
              <template v-slot:form-informedTime>
                <el-date-picker
                  v-model="formInfo.data.informedTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择发现获知时间"
                />
              </template>
            </page-form>
          </div>
        </div>

        <!-- 使用信息 -->
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('useInfo') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.useInfoRef"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.useInfoFieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-useTime>
                <el-date-picker
                  v-model="formInfo.data.useTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择器械使用时间"
                />
              </template>
            </page-form>
          </div>
        </div>

        <!-- 初步原因分析及处置 -->
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('preliminaryAnalysisInfo') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.preliminaryAnalysisInfoRef"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.preliminaryAnalysisInfoFieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
            </page-form>
          </div>
        </div>
      </NewFullScreen>
    </div>

    <!-- 选择资产 -->
    <Select-asset
      v-if="assetArchivesInfo.visible"
      v-model:show-dialog="assetArchivesInfo.visible"
      :query="assetArchivesInfo.query.queryMap"
      :check-box="false"
      :highlight-row="true"
      row-key="id"
      :table-key="assetArchivesInfo.tableKey"
      @callback="callbackAsset"
    />
    <SelectAdverseEvent
      v-if="selectAdverseInfo.visible"
      v-model:show-dialog="selectAdverseInfo.visible"
      :query="selectAdverseInfo.query.queryMap"
      :check-box="false"
      :highlight-row="true"
      row-key="id"
      :table-key="selectAdverseInfo.tableKey"
      @callback="callbackAdverse"
    />
  </div>
</template>

<script setup name="adverseEventModify">
import PageForm from '@/components/PageForm/index'
import {
  createAdverseEvent,
  createAdverseEventAndSave,
  getAdverseEvent,
  updateAdverseEvent,
  submitAdverseEvent,
} from '@/api/quality'
import selectAsset from '@/components/SelectAsset/index'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps(['visible', 'id', 'flowFormType', 'title'])
const isFinite = ref(false)
//校验发生时间
const validateHappenTime = (rule, value, callback) => {
  if (value) {
    if (new Date(value).getTime() > Date.now()) {
      callback(new Error('事件发生时间不能大于当前时间'))
    }
    callback()
  } else {
    callback()
  }
}
//校验发现获知时间
const validateInformedTime = (rule, value, callback) => {
  let happenTime = formInfo.value.data.happenTime
  if (!happenTime) {
    callback(new Error('请先选择事件发生时间'))
  } else {
    if (value) {
      if (new Date(value).getTime() < new Date(happenTime).getTime()) {
        callback(new Error('发现获知时间不能小于事件发生时间'))
      }
      if (new Date(value).getTime() > Date.now()) {
        callback(new Error('发现获知时间不能大于当前时间'))
      }
      callback()
    } else {
      callback()
    }
  }
}
//校验器械使用时间
const validateUseTime = (rule, value, callback) => {
  let happenTime = formInfo.value.data.happenTime
  if (!happenTime) {
    callback(new Error('请先选择事件发生时间'))
  } else {
    if (value) {
      if (new Date(value).getTime() > new Date(happenTime).getTime()) {
        callback(new Error('器械使用时间不能大于事件发生时间'))
      }
      if (new Date(value).getTime() > Date.now()) {
        callback(new Error('器械使用时间不能大于当前时间'))
      }
      callback()
    } else {
      callback()
    }
  }
}

//选择资产弹窗相关
const assetArchivesInfo = reactive({
  visible: false,
  tableKey: 'AdverseEventAddCoreAsset-com.slip.spd.entity.vo.core.CoreAssetVO',
  query: {
    queryMap: {
      //状态
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '3',
      },
      //资产状态
      assetStatus: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '1,3',
      },
      // 锁定
      isLocked: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
      //是否计量
      isMetering: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
    },
    queryParams: {},
  },
})
const selectAdverseInfo = reactive({
  visible: false,
  query: {
    queryMap: {},
    queryParams: {},
  },
})
//表单相关
const formInfo = ref({
  baseRef: null,
  adverseEventRef: null,
  useInfoRef: null,
  preliminaryAnalysisInfoRef: null,
  data: {
    type: '',
    deviceId: '',
    deviceName: '',
    measuringInstrumentId: '',
    measuringInstrumentName: '',
    deviceDeptId: '',
    deviceDeptName: '',
    deviceCode: '',
    deviceSn: '',
    model: '',
    productId: '',
    productName: '',
    productionDate: '',
    batchNumber: '',
    registerNo: '',
    deviceAddress: '',
  },
  fieldList: [
    {
      label: '类型',
      value: 'type',
      type: 'radio-model',
      code: 'adverse_event_reporting_type_enum',
    },
    { label: '计量器具ID', value: 'measuringInstrumentId', show: false },
    {
      label: '计量器具',
      value: 'measuringInstrumentName',
      type: 'slot',
      show: false,
    },
    { label: '设备ID', value: 'deviceId', show: false },
    { label: '设备', value: 'deviceName', type: 'slot', show: true },
    {
      label: '使用部门',
      value: 'deviceDeptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '设备位置',
      value: 'deviceAddress',
      type: 'input',
      disabled: true,
    },
    { label: 'SN', value: 'deviceSn', type: 'input', disabled: true },
    { label: '设备编码', value: 'deviceCode', type: 'input', disabled: true },
    { label: '产品ID', value: 'productId', show: false },
    { label: '产品名称', value: 'productName', type: 'input' },
    { label: '注册证号', value: 'registerNo', type: 'input' },
    { label: '规格', value: 'model', type: 'input' },
    { label: '生产批号', value: 'batchNumber', type: 'input' },
    { label: '生产日期', value: 'productionDate', type: 'date' },
    { label: '失效日期', value: 'validityDate', type: 'date' },
  ],
  adverseEventFieldList: [
    { label: '事件发生时间', value: 'happenTime', type: 'slot' },
    { label: '发现获知时间', value: 'informedTime', type: 'slot' },
    {
      label: '伤害',
      value: 'hurtType',
      type: 'select-model',
      code: 'hurt_type',
    },
    {
      label: '伤害表现',
      value: 'hurtPerformance',
      type: 'textarea',
    },
    {
      label: '器械故障表现',
      value: 'fault',
      type: 'textarea',
    },
    { label: '姓名', value: 'name', type: 'input' },
    { label: '出生日期', value: 'birthDate', type: 'date' },
    { label: '年龄', value: 'age', type: 'number' },
    { label: '性别', value: 'sex', type: 'select-model', code: 'sex' },
    { label: '病历号', value: 'medicalRecordNo', type: 'input' },
    {
      label: '既往病史',
      value: 'pastMedicalHistory',
      type: 'textarea',
    },
  ],
  useInfoFieldList: [
    { label: '器械使用时间', value: 'useTime', type: 'slot' },
    {
      label: '使用场所',
      value: 'useAddressType',
      type: 'select-model',
      code: 'use_address_type',
    },
    { label: '场所名称', value: 'addressName', type: 'input' },
    {
      label: '预期治疗疾病或作用',
      value: 'effect',
      type: 'textarea',
    },
    {
      label: '使用过程',
      value: 'process',
      type: 'textarea',
    },
    {
      label: '合并用药/械情况说明',
      value: 'consolidation',
      type: 'textarea',
    },
  ],
  preliminaryAnalysisInfoFieldList: [
    {
      label: '事件原因分析',
      value: 'causeAnalysisType',
      type: 'radio-model',
      code: 'cause_analysis_type',
      className: 'not-br',
    },
    {
      label: '事件原因分析描述',
      value: 'causeAnalysisDescribe',
      type: 'textarea',
    },
    {
      label: '初步处置情况',
      value: 'handleSituation',
      type: 'textarea',
    },
  ],
  rules: {
    measuringInstrumentName: [
      { required: true, message: '请选择计量器具', trigger: 'change' },
    ],
    deviceName: [{ required: true, message: '请选择设备', trigger: 'change' }],
    happenTime: [
      { required: true, message: '请选择事件发生时间', trigger: 'change' },
      { validator: validateHappenTime, trigger: 'blur' },
    ],
    informedTime: [
      { required: true, message: '请选择发现获知时间', trigger: 'change' },
      { validator: validateInformedTime, trigger: 'blur' },
    ],
    hurtType: [
      { required: true, message: '请选择伤害类型', trigger: 'change' },
    ],
    useTime: [
      { required: true, message: '请选择器械使用时间', trigger: 'change' },
      { validator: validateUseTime, trigger: 'blur' },
    ],
    useAddressType: [
      { required: true, message: '请选择使用场所', trigger: 'change' },
    ],
    causeAnalysisType: [
      { required: true, message: '请选择事件原因分析', trigger: 'change' },
    ],
  },
  labelWidth: '120px',
})
const detailInfo = reactive({
  visible: false,
  id: '',
  title: '不良事件详情',
})
const formRefs = ref('')
const assetDetailInfo = ref('')

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
watch(
  () => formInfo.value.data.type,
  (val) => {
    if (isFinite.value) {
      formInfo.value.data.deviceDeptId = ''
      formInfo.value.data.deviceDeptName = ''
      formInfo.value.data.deviceCode = ''
      formInfo.value.data.deviceSn = ''
      formInfo.value.data.model = ''
      formInfo.value.data.productId = ''
      formInfo.value.data.productName = ''
      formInfo.value.data.batchNumber = ''
      formInfo.value.data.productionDate = ''
      formInfo.value.data.registerNo = ''
      formInfo.value.data.deviceAddress = ''

      formInfo.value.data.deviceName = ''
    }
    if (val == 1) {
      showFinanceFieldListItem(false, 'deviceName')
      showFinanceFieldListItem(true, 'measuringInstrumentName')
      if (isFinite.value) {
        formInfo.value.data.deviceId = ''
      }
    } else {
      if (isFinite.value) {
        formInfo.value.data.measuringInstrumentId = ''
        formInfo.value.data.measuringInstrumentName = ''
      }
      showFinanceFieldListItem(true, 'deviceName')
      showFinanceFieldListItem(false, 'measuringInstrumentName')
    }
    console.log(formInfo.value.fieldList)
  }
)
function showFinanceFieldListItem(show, nameValue) {
  let fieldList = formInfo.value.fieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}

onMounted(() => {
  formRefs.value = [
    formInfo.value.baseRef,
    formInfo.value.adverseEventRef,
    formInfo.value.useInfoRef,
    formInfo.value.preliminaryAnalysisInfoRef,
  ]
  if (props.id) {
    getMain()
  } else {
    isFinite.value = true
  }
})

function callbackAdverse(row) {
  formInfo.value.data.measuringInstrumentId = row.id
  formInfo.value.data.measuringInstrumentName = row.commonName

  formInfo.value.data.deviceDeptId = ''
  formInfo.value.data.deviceDeptName = ''
  formInfo.value.data.deviceSn = ''
  formInfo.value.data.deviceAddress = ''
  formInfo.value.data.batchNumber = ''
  formInfo.value.data.model = row.standard

  formInfo.value.data.deviceCode = row.code
  formInfo.value.data.productId = row.productId
  formInfo.value.data.productName = row.productName
  formInfo.value.data.productionDate = row.licenseBeginDate
  formInfo.value.data.validityDate = row.licenseEndDate
  formInfo.value.data.registerNo = row.licenseNumber

  formInfo.value.data.deviceId = ''
  formInfo.value.data.deviceName = row.commonName
}
function callbackAsset(row) {
  formInfo.value.data.deviceId = row.id
  formInfo.value.data.deviceName = row.assetName
  formInfo.value.data.deviceDeptId = row.useDeptId
  formInfo.value.data.deviceDeptName = row.useDeptNameRate
  formInfo.value.data.deviceCode = row.assetCode
  formInfo.value.data.deviceSn = row.machineCode
  formInfo.value.data.model = row.standard
  formInfo.value.data.productId = row.productId
  formInfo.value.data.productName = row.productName
  formInfo.value.data.batchNumber = row.batchNumber
  formInfo.value.data.productionDate = row.productionDate
  formInfo.value.data.registerNo = row.registerCode
  formInfo.value.data.deviceAddress = row.location

  formInfo.value.data.measuringInstrumentId = ''
  formInfo.value.data.measuringInstrumentName = ''
}
function openAssetArchivesDialog() {
  assetArchivesInfo.visible = true
}
function openAdverseDialog() {
  selectAdverseInfo.visible = true
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function showAssetDetail(row) {
  assetDetailInfo.value.id = row.assetId
  assetDetailInfo.value.visible = true
}
function getMain() {
  getAdverseEvent(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      formInfo.value.data.measuringInstrumentName = resp.data.deviceName
      setTimeout(() => {
        isFinite.value = true
      }, 0)
    }
  })
}
// flowData 外部流程页面调用
function saveAndSubmit(flowData) {
  save(true, flowData)
}
function save(isSaveAndSubmit, obj = {}) {
  formRefs.value = [
    formInfo.value.baseRef,
    formInfo.value.adverseEventRef,
    formInfo.value.useInfoRef,
    formInfo.value.preliminaryAnalysisInfoRef,
  ]
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let api = props.id
      ? updateAdverseEvent
      : isSaveAndSubmit === true
      ? createAdverseEventAndSave
      : createAdverseEvent
    let flowParams = { ...formInfo.value.data }
    if (isSaveAndSubmit === true) {
      if (proxy.$route.query.processInstanceId) {
        api = submitAdverseEvent
      }
      flowParams = {
        orderData: flowParams,
        // flowTaskCommentDto和processDefinitionKey为审批流程需要传递的参数
        flowTaskCommentDto: { approvalType: 'submit' },
        processDefinitionKey: 'adverseEvent',
        processInstanceId: obj.processInstanceId,
        taskId: obj.taskId,
      }
    }
    api(flowParams).then((res) => {
      if (res && res.success) {
        showDialog.value = false
        emit('returnModify', false)
      }
    })
  })
}
// 名称不要做改变，在流程引擎中需要通过refs进行调用
defineExpose({
  save,
  saveAndSubmit,
})
</script>

<style scoped lang="scss">
:deep(.page-table > .el-table) {
  overflow: hidden;
}
</style>
